<div class="tmd-doc">
<h1 class="tmd-header-1">
Line Break Rules in Go
</h1>
<p></p>
<div class="tmd-usual">
If you have written go code much, you should have known that we can't use arbitrary code styles in Go programming. Specifically speaking, we can't break a code line at an arbitrary space character position. The remaining of this article will list the detailed line break rules in Go.
</div>
<p></p>
<h3 class="tmd-header-3">
Semicolon Insertion Rules
</h3>
<p></p>
<div class="tmd-usual">
One rule we often obey in practice is, we should not put the a starting curly brace (<code class="tmd-code-span">{</code>) of any explicit code block on a new line. For example, the following <code class="tmd-code-span">for</code> loop code block fails to compile.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	for i := 5; i &gt; 0; i--
	{ // unexpected newline, expecting { after for clause
	}
</code></pre>
<p></p>
<div class="tmd-usual">
To make it compiles okay, the starting curly brace mustn't be put on a new line, like the following:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	for i := 5; i &gt; 0; i-- {
	}
</code></pre>
<p></p>
<div class="tmd-usual">
However, there are some exceptions for the rule mentioned above. For example, the following bare <code class="tmd-code-span">for</code> loop block compiles okay.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	for
	{
		// do something ...
	}
</code></pre>
<p></p>
<div class="tmd-usual">
Then, what are the fundamental rules to do line breaks in Go programming? Before answering this question, we should know a fact that the formal Go grammar uses semicolons <code class="tmd-code-span">;</code> as terminators of code lines. However, we seldom use semicolons in our Go code. Why? The reason is most semicolons are optional and can be omitted. Go compilers will insert the omitted semicolons for us automatically in compiling.
</div>
<p></p>
<div class="tmd-usual">
For example, the ten semicolons in the following program are all optional.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main;

import "fmt";

func main() {
	var (
		i   int;
		sum int;
	);
	for i &lt; 6 {
		sum += i;
		i++;
	};
	fmt.Println(sum);
};
</code></pre>
<p></p>
<div class="tmd-usual">
Assume the above program is stored in a file named <code class="tmd-code-span">semicolons.go</code>, we can run <code class="tmd-code-span">go fmt semicolons.go</code> to remove all the unnecessary semicolons from that file. Compilers will insert the removed semicolons back (in memory) automatically in compiling the source code.
</div>
<p></p>
<div class="tmd-usual">
What are the semicolons insertion rules in Go? Let's read <a href="https://golang.org/ref/spec#Semicolons">the semicolon rules listed in Go specification</a>.
</div>
<p></p>
<p></p>
<div class="tmd-base alert alert-success">
<div class="tmd-usual">
The formal grammar uses semicolons ";" as terminators in a number of productions. Go programs may omit most of these semicolons using the following two rules:
</div>
<p></p>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
When the input is broken into tokens, a semicolon is automatically inserted into the token stream immediately after a line's final token if that token is
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
an <a href="keywords-and-identifiers.html#identifier">identifier</a>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
an integer, floating-point, imaginary, rune, or string <a href="basic-types-and-value-literals.html#basic-value-literals">literal</a>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
one of the keywords <code class="tmd-code-span">break</code>, <code class="tmd-code-span">continue</code>, <code class="tmd-code-span">fallthrough</code>, or <code class="tmd-code-span">return</code>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
one of the operators and punctuation <code class="tmd-code-span">++</code>, <code class="tmd-code-span">--</code>, <code class="tmd-code-span">)</code>, <code class="tmd-code-span">]</code>, or <code class="tmd-code-span">}</code>
</div>
</li>
</ul>
<p></p>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
To allow complex statements to occupy a single line, a semicolon may be omitted before a closing <code class="tmd-code-span">)</code> or <code class="tmd-code-span">}</code>.
</div>
</li>
</ol>
</div>
<p></p>
<div class="tmd-usual">
For the scenarios listed in the first rule, surely, we can also insert the semicolons manually, just like the semicolons in the last code example. In other words, these semicolons are optional in programming.
</div>
<p></p>
<div class="tmd-usual">
The second rule means the last semicolon in a multi-item declaration before the closing sign <code class="tmd-code-span">)</code> and the last semicolon within a code block or a (struct or interface) type declaration before the closing sign <code class="tmd-code-span">}</code> are optional. If the last semicolon is absent, compilers will automatically insert it back.
</div>
<p></p>
<div class="tmd-usual">
The second rule lets us be able to write the following valid code.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">import (_ "math"; "fmt")
var (a int; b string)
const (M = iota; N)
type (MyInt int; T struct{x bool; y int32})
type I interface{m1(int) int; m2() string}
func f() {print("a"); panic(nil)}
</code></pre>
<p></p>
<div class="tmd-usual">
Compilers will automatically insert the omitted semicolons for us, as the following code shows.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var (a int; b string;);
const (M = iota; N;);
type (MyInt int; T struct{x bool; y int32;};);
type I interface{m1(int) int; m2() string;};
func f() {print("a"); panic(nil);};
</code></pre>
<p></p>
<div class="tmd-usual">
Compilers will not insert semicolons for any other scenarios. We must insert the semicolons manually as needed for other scenarios. For example, the first semicolon at each line in the last code example are all required. The semicolons in the following example are also required.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var a = 1; var b = true
a++; b = !b
print(a); print(b)
</code></pre>
<p></p>
<div class="tmd-usual">
From the two rules, we know that a semicolon will never be inserted just after the <code class="tmd-code-span">for</code> keyword. This is why the bare <code class="tmd-code-span">for</code> loop example shown above is valid.
</div>
<p></p>
<div class="tmd-usual">
One consequence of the semicolon insertion rules is that the self increment and self decrement operations must appear as statements. They can't be used as expressions. For example, the following code is invalid.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">func f() {
	a := 0
	// The following two lines both fail to compile.
	println(a++) // unexpected ++, expecting comma or )
	println(a--) // unexpected --, expecting comma or )
}
</code></pre>
<p></p>
<div class="tmd-usual">
The reason why the above code is invalid is compilers will view it as
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">func f() {
	a := 0;
	println(a++;);
	println(a--;);
}
</code></pre>
<p></p>
<div class="tmd-usual">
Another consequence of the semicolon insertion rules is we can't break a line before the dot <code class="tmd-code-span">.</code> in a selector. We can only break a line after the dot, as the following code shows
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	anObject.
		MethodA().
		MethodB().
		MethodC()
</code></pre>
<p></p>
<div class="tmd-usual">
whereas the following code fails to compile.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	anObject
		.MethodA()
		.MethodB()
		.MethodC()
</code></pre>
<p></p>
<div class="tmd-usual">
Compilers will insert a semicolon at the end of each line in the modified version, so the above code is equivalent to the following code which is obviously invalid.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	anObject;
		.MethodA();
		.MethodB();
		.MethodC();
</code></pre>
<p></p>
<div class="tmd-usual">
The semicolon insertion rules make us write cleaner code. They also make it is possible to write some valid but a little weird code. For example,
</div>
<p></p>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">package main

import "fmt"

func alwaysFalse() bool {return false}

func main() {
	for
	i := 0
	i &lt; 6
	i++ {
		// use i ...
	}

	if x := alwaysFalse()
	!x {
		// do something ...
	}

	switch alwaysFalse()
	{
	case true: fmt.Println("true")
	case false: fmt.Println("false")
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
All the three control flow blocks are valid. Compilers will insert a semicolon at the end of each of line <span class="tmd-italic">9</span>, <span class="tmd-italic">10</span>, <span class="tmd-italic">15</span> and <span class="tmd-italic">20</span>.
</div>
<p></p>
<div class="tmd-usual">
Please note, the <code class="tmd-code-span">switch-case</code> block in the above example will print a <code class="tmd-code-span">true</code> instead of a <code class="tmd-code-span">false</code>. It is different from
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	switch alwaysFalse() {
	case true: fmt.Println("true")
	case false: fmt.Println("false")
	}
</code></pre>
<p></p>
<div class="tmd-usual">
If we use the <code class="tmd-code-span">go fmt</code> command to format the former one, a semicolon will be appended automatically after the <code class="tmd-code-span">alwaysFalse()</code> call, so it will become to
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	switch alwaysFalse();
	{
	case true: fmt.Println("true")
	case false: fmt.Println("false")
	}
</code></pre>
<p></p>
<div class="tmd-usual">
The modified version is equivalent to the following one.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">	switch alwaysFalse(); true {
	case true: fmt.Println("true")
	case false: fmt.Println("false")
	}
</code></pre>
<p></p>
<div class="tmd-usual">
That is why it will print a <code class="tmd-code-span">true</code>.
</div>
<p></p>
<div class="tmd-usual">
It is a good habit to run <code class="tmd-code-span">go fmt</code> and <code class="tmd-code-span">go vet</code> often for your code.
</div>
<p></p>
<div class="tmd-usual">
For a rare case, the semicolon insertion rules also make some code look valid but invalid actually. For example, the following code snippet fails to compile.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">func f(x int) {
	switch x {
	case 1:
	{
		goto A
		A: // compiles okay
	}
	case 2:
		goto B
		B: // syntax error: missing statement after label
	case 0:
		goto C
		C: // compiles okay
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
The compilation error message indicates that there must be a statement following a label declaration. But it looks none label in the above example is followed by a statement. Why is only the <code class="tmd-code-span">B:</code> label declaration invalid? The reason is, by the second semicolon insertion rule mentioned above, compilers will insert a semicolon before each of the <code class="tmd-code-span">}</code> characters following the <code class="tmd-code-span">A:</code> and <code class="tmd-code-span">C:</code> label declarations. As the following code shows.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">func f(x int) {
	switch x {
	case 1:
	{
		goto A
		A:
	;} // a semicolon is inserted here
	case 2:
		goto B
		B: // syntax error: missing statement after label
	case 0:
		goto C
		C:
	;} // a semicolon is inserted here
}
</code></pre>
<p></p>
<div class="tmd-usual">
A solo semicolon represents a <a href="expressions-and-statements.html#simple-statements">blank statement</a> actually, which is why the <code class="tmd-code-span">A:</code> and <code class="tmd-code-span">C:</code> label declarations are both valid. On the other hand, the <code class="tmd-code-span">B:</code> label declaration is followed by <code class="tmd-code-span">case 0:</code>, which is not a statement, so the <code class="tmd-code-span">B:</code> label declaration is invalid.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
We can manually insert a semicolon (a blank statement) at the end of each of the <code class="tmd-code-span">B:</code> label declaration to make it compile okay.
</div>
<p></p>
<h3 id="commas" class="tmd-header-3">
Comma (<code class="tmd-code-span">,</code>) Will Not Be Inserted Automatically
</h3>
<p></p>
<div class="tmd-usual">
In some syntax forms containing multiple alike items, commas are used as separators, such as composite literals, function argument lists, function parameter lists and function result lists. In such a syntax form, the last item can always be followed by a comma. If the following comma is the last effective character in its respective code line, then the comma is required, otherwise, it is optional. Compilers will not insert commas automatically for any cases.
</div>
<p></p>
<div class="tmd-usual">
For example, the following code snippet is valid.
</div>
<p></p>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">func f1(a int, b string,) (x bool, y int,) {
	return true, 789
}
var f2 func (a int, b string) (x bool, y int)
var f3 func (a int, b string, // the last comma is required
) (x bool, y int,             // the last comma is required
)
var _ = []int{2, 3, 5, 7, 9,} // the last comma is optional
var _ = []int{2, 3, 5, 7, 9,  // the last comma is required
}
var _ = []int{2, 3, 5, 7, 9}
var _, _ = f1(123, "Go",) // the last comma is optional
var _, _ = f1(123, "Go",  // the last comma is required
)
var _, _ = f1(123, "Go")
// The same for explicit conversions.
var _ = string(65,) // the last comma is optional
var _ = string(65,  // the last comma is required
)
</code></pre>
<p></p>
<div class="tmd-usual">
However, the following code snippet is invalid, for compilers will insert a semicolon for each line in the code, except the second line. There are three lines which will cause <code class="tmd-code-span">unexpected newline</code> syntax errors.
</div>
<p></p>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">func f1(a int, b string,) (x bool, y int // error
) {
	return true, 789
}
var _ = []int{2, 3, 5, 7 // error: unexpected newline
}
var _, _ = f1(123, "Go" // error: unexpected newline
)
</code></pre>
<p></p>
<h3 class="tmd-header-3">
Final Words
</h3>
<p></p>
<div class="tmd-usual">
At the end, let's describe the line break rules in Go according to the above explanations.
</div>
<p></p>
<div class="tmd-base alert alert-success">
<div class="tmd-usual">
In Go, a line break is okay (will not affect code behavior) if:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
it happens immediately after a keyword other than <code class="tmd-code-span">break</code>, <code class="tmd-code-span">continue</code> and <code class="tmd-code-span">return</code>, or after any of the three keywords which are not followed by labels or return results;
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
it happens immediately after a semicolon, whether the semicolon is inserted explicitly or implicitly;
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
it doesn't lead to an implicit semicolon will be inserted.
</div>
</li>
</ul>
</div>
<p></p>
<div class="tmd-usual">
Like some other design details in Go, there are both praises and criticisms for the semicolon insertion rules. Some programmers don't like the rules, for they think the rules limit the freedom of code styles. Praisers think the rules make code compile faster, and make the code written by different programmers look similar, so that it is easy to understand the code written by each other.
</div>
<p></p>
</div>
